import {defineStore} from 'pinia';
import {Chatting, ContactsItem, GroupItem, User} from '../models/chat_model.ts';
import {toRaw} from "vue";
import {chattingList} from "@/api/data_mock.js";

// 定义 state 类型
interface ChatStoreState {
    user?: User | null;
    chatList: Chatting[];
}

// 定义一个 name 为‘blogStore’的 store
export const useChatStore = defineStore('chatStore', {
    // 第三方插件的持久化配置
    // persist: {
    //     enabled: true,
    //     strategies: [{
    //         storage: sessionStorage
    //     }]
    // },
    state: (): ChatStoreState => {
        return {
            user: null, //当前user
            // 聊天列表数据
            chatList: [], // 聊天列表数据
        };
    },
    getters: {
        getChatList(state): any[] {
            return state.chatList;
        },
    },
    actions: {
        /**
         * 重新加载数据
         * @param user
         */
        async reloadData(user: User) {
            console.debug("refreshChattingList ...")
            this.user = user;
            //mock 数据
            this.chatList = chattingList(user);
        }

        , getChattingByRelId(relId: string, isGroup: boolean) {
            if (!relId) {
                new Error("relId 不能为空");
            }
            console.debug(">> getChattingByRelId.. relId = " + relId)

            return this.chatList.filter(chat => chat.isGroup == isGroup)
                .find(chat => {
                    return (String(chat.relId) === String(relId));
                })
        }

        /**
         * 添加聊天对象到列表首位
         * @param chatContext
         */
        , addToChatList(chatting: Chatting) {
            let exist = this.chatList
                .filter(chat => chat.isGroup == chatting.isGroup)
                .find(chat => {
                    return String(chat.relId) === String(chatting.relId) || (!chatting.isGroup && (String(chat.peerUserId) === String(chatting.peerUserId)));
                });
            //为了兼容数据更改
            if (exist) {
                exist.relId = chatting.relId;
                if (chatting.isGroup) {
                    exist.peerUserId = chatting.peerUserId;
                }
            } else {
                this.chatList.push(chatting); //添加到数组中
            }

        }

        , obtainChatting(chatter: ContactsItem | GroupItem) {
            console.debug("obtainChatting ... chatter.relId = " + chatter.relId);
            const isGroup = ("groupNo" in chatter);

            let chatting = this.getChattingByRelId(chatter.relId, isGroup);
            if (!chatting) {
                console.debug("create Chatting ... ");
                if (!this.user) {
                    new Error("user数据不能为空")
                }
                //取不到别名就取昵称
                const showName = isGroup ? (chatter as GroupItem).name : ((chatter as ContactsItem).aliasName ? (chatter as ContactsItem).aliasName : (chatter as ContactsItem).nickname);
                chatting = new Chatting(toRaw(this.user!), chatter.relId, showName, chatter.avatarUrl, isGroup);
                if (!isGroup) {
                    chatting.peerUserId = (chatter as ContactsItem).userId;
                    if (!chatting.peerUserId) {
                        console.error("chatting.peerUserId不能为空,出现数据错误 chatter = ", chatter)
                    }
                }
                this.addToChatList(chatting);
            } else {
                console.debug("without create Chatting ... ");
            }
            return chatting;
        }
    }
});